﻿//if (window.document.domain != "localhost" && window.document.domain != "172.16.7.40" && window.document.domain != "10.0.8.60" && window.document.domain != "10.0.8.61" && window.document.domain != "10.0.7.119") {
//    window.document.domain = "xincheng.com"
//}

$.stopBubble = function (e) {
    //如果提供了事件对象，则这是一个非IE浏览器 
    if (e && e.stopPropagation)
        //因此它支持W3C的stopPropagation()方法 
        e.stopPropagation();
    else
        //否则，我们需要使用IE的方式来取消事件冒泡 
        window.event.cancelBubble = true;
}
//ajax请求错误处理方法
$.ajaxErrorProcess = function (jqXHR) {
    $.loading(false);
    switch (jqXHR.status) {
        case (500):
            $.modalAlert("服务器系统内部错误");
            break;
        case (401):
            $.modalAlert("未登录");
            break;
        case (403):
            $.modalAlert("无权限执行此操作");
            break;
        case (408):
            $.modalAlert("请求超时");
            break;
        default:
            $.modalAlert("未知错误");
    }
}
//重新加载页面
$.reload = function () {
    location.reload();
    return false;
}
$.refreshParentPage = function () {
    try {
        if (window.opener && !window.opener.closed)
            window.opener.location.href = window.opener.location.href;
    }
    catch (ex) { }
    finally {
        window.opener = null;
    }

}
//关闭页面(刷新父页面可选)
$.closePage = function (refreshParent) {
    if (typeof (refreshParent) == "undefined") {
        refreshParent = false;
    }
    if (navigator.userAgent.indexOf("MSIE") > 0) {
        if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {

            if (refreshParent) {
                $.refreshParentPage();
            }
            window.opener = null;
            window.close();
        } else {
            window.open('', '_top');
            if (refreshParent) {
                $.refreshParentPage();
            }
            window.top.close();
            try {
                $.reload();
            } catch (e) {

            }
        }
    }
    else if (navigator.userAgent.indexOf("Firefox") > 0 || navigator.userAgent.indexOf("Chrome") > 0) {
        if (refreshParent) {
            $.refreshParentPage();
        }
        window.close();
        try {
            $.reload();
        } catch (e) {

        }
    }
    else {
        window.open('', '_self');
        if (refreshParent) {
            $.refreshParentPage();
        }
        window.close();
        try {
            $.reload();
        } catch (e) {

        }
    }
}
//加载中效果
$.loading = function (bool, text, callback) {
    var $loadingpage = $(".loadingPanel");
    var $loadingtext = $loadingpage.find('.loading-content');
    if (bool) {
        $("#overlay").height($.windowHeight() > $.pageHeight() + 40 ? $.windowHeight() : $.pageHeight() + 40);
        $("#overlay").width($.winddowWidth() > $.pageWidth() + 40 ? $.winddowWidth() : $.pageWidth() + 40);

        // fadeTo第一个参数为速度，第二个为透明度
        // 多重方式控制透明度，保证兼容性，但也带来修改麻烦的问题
        $("#overlay").fadeTo(200, 0.5);
        $loadingpage.show();
    } else {
        if ($loadingtext.attr('istableloading') == undefined) {
            $("#overlay").fadeOut(200);
            $loadingpage.hide();
            if (!!callback) {
                callback();
            }
        }
    }
    if (!!text) {
        $loadingtext.html(text);
    } else {
        $loadingtext.html("数据加载中，请稍后…");
    }
    //始终显示在窗体中间
    var top = ($(window).height() - $loadingtext.height()) / 2;
    var left = ($(window).width() - $loadingtext.width()) / 2;
    var scrollTop = $(document).scrollTop();
    var scrollLeft = $(document).scrollLeft();
    $loadingtext.css("left", left + scrollLeft);
    $loadingtext.css("top", top);
}
//从url中获取参数
$.request = function (name) {
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == name) {
            if (unescape(ar[1]) == 'undefined') {
                return "";
            } else {
                return unescape(ar[1]);
            }
        }
    }
    return "";
}
//判断浏览器
$.browser = function () {
    var userAgent = navigator.userAgent;
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    };
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    }
    if (userAgent.indexOf("Chrome") > -1) {
        if (window.navigator.webkitPersistentStorage.toString().indexOf('DeprecatedStorageQuota') > -1) {
            return "Chrome";
        } else {
            return "360";
        }
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    }
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    };
}
//根据一个URL打开对话框
$.modalOpenURL = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        shade: 0.3,
        btn: ['确认', '关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null
    };
    var options = $.extend(defaults, options);
    var _width = $(window).width() > parseInt(options.width.replace('px', '')) ? options.width : $(window).width() + 'px';
    var _height = $(window).height() > parseInt(options.height.replace('px', '')) ? options.height : $(window).height() + 'px';
    layer.open({
        id: options.id,
        type: 2,
        shade: options.shade,
        title: options.title,
        fix: false,
        area: [_width, _height],
        content: options.url,
        btn: options.btn,
        btnclass: options.btnclass,
        yes: function () {
            options.callBack(options.id)
        }, cancel: function () {
            return true;
        }
    });
}
//弹出一个对话框，根据content
$.modalOpen = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "250px",
        height: "200px",
        content: '',
        shade: 0.3,
        btn: ['确认', '关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null,
        cancelCallBack: null,
        success: null,
        zIndex:1000
    };
    var options = $.extend(defaults, options);
    var _width = $(window).width() > parseInt(options.width.replace('px', '')) ? options.width : $(window).width() + 'px';
    var _height = $(window).height() > parseInt(options.height.replace('px', '')) ? options.height :$(window).height() + 'px';
    layer.open({
        id: options.id,
        type: 1,
        shade: options.shade,
        title: options.title,
        fix: true,
        area: [_width, _height],
        content: options.content,
        btn: options.btn,
        btnclass: options.btnclass,
        yes: function (index, layero) {
            options.callBack(options.id, index);
        },
        btn2: function (index, layero) {
            if (options.cancelCallBack != null) {
                options.cancelCallBack(options.id);
            }
        },
        cancel: function () {
            if (options.cancelCallBack != null) {
                options.cancelCallBack(options.id);
            }
        },
        end: function () {
            if (options.end instanceof Function) {
                options.end();
            }
        },
        success: options.success,
        zIndex: options.zIndex
    });
}
//弹出一个确认框
$.modalConfirm = function (content, callBack) {
    layer.confirm(content, {
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
    }, function () {
        callBack(true);
    }, function () {
        callBack(false)
    });
}
//弹出一个警告框
$.modalAlert = function (content, type, callback, endFunction) {
    var icon = "";
    if (type == 'success') {
        icon = "fa-check-circle";
    }
    if (type == 'error') {
        icon = "fa-times-circle";
    }
    if (type == 'warning') {
        icon = "fa-exclamation-circle";
    }
    layer.alert(content, {
        icon: icon,
        title: "系统提示",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
        end: function () {
            if (endFunction instanceof Function) {
                endFunction();
            }
        },
    }, function (index) {
        layer.close(index);
        if (!!callback) {
            callback();
        }

    });
}
//弹出一个消息框
$.modalMsg = function (content, type, callback) {
    if (type != undefined || type == "") {
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }
        $(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
        layer.msg(content, { time: 3000, shift: 5 }, function () {
            if (!!callback) {
                callback();
            }
        });
    } else {
        layer.msg(content, { time: 3000 }, function () {
            if (!!callback) {
                callback();
            }
        });
    }
};
$.modalClose = function (index) {
    layer.close(index); //执行关闭   
};


//序列化和反序列化表单
$.fn.formSerialize = function (formdate) {
    var element = $(this);
    if (!!formdate) {
        for (var key in formdate) {
            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            switch (type) {
                case "checkbox":
                    if (value == "true") {
                        $id.attr("checked", 'checked');
                    } else {
                        $id.removeAttr("checked");
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;
                default:
                    $id.val(value);
                    break;
            }
        };
        return false;
    }
    var postdata = {};
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var name = $this.attr('name');
        var type = $this.attr('type');
        if (name == undefined) {
            return true;
        }
        if ($this.attr("noSerialize") == "true") {
            return true;
        }
        switch (type) {
            case "checkbox":
                postdata[name] = $this.is(":checked");
                break;
            case "radio":
                if ($this.is(":checked")) {
                    postdata[name] = $this.val();
                }

                break;
            default:
                var value = $this.val() == "" ? "&nbsp;" : $this.val();
                if (!$.request("keyValue") && (!!value)) {
                    value = value.replace(/&nbsp;/g, '');
                }
                postdata[name] = value;
                break;
        }
    });
    if ($('[name=__RequestVerificationToken]').length > 0) {
        postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    return postdata;
};

//提交表单相关方法
$.submitForm = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.state == "success") {
                    options.success(data);
                    $.modalMsg(data.message, data.state);
                    if (options.close == true) {
                        $.modalClose();
                    }
                } else {
                    $.modalAlert(data.message, data.state);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}
$.deleteForm = function (options) {
    var defaults = {
        prompt: "注：您确定要删除该项数据吗？",
        url: "",
        param: [],
        loading: "正在删除数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    if ($('[name=__RequestVerificationToken]').length > 0) {
        options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    $.modalConfirm(options.prompt, function (r) {
        if (r) {
            $.loading(true, options.loading);
            window.setTimeout(function () {
                $.ajax({
                    url: options.url,
                    data: options.param,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            options.success(data);
                            $.modalMsg(data.message, data.state);
                        } else {
                            $.modalAlert(data.message, data.state);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.loading(false);
                        $.modalMsg(errorThrown, "error");
                    },
                    beforeSend: function () {
                        $.loading(true, options.loading);
                    },
                    complete: function () {
                        $.loading(false);
                    }
                });
            }, 500);
        }
    });

}
//绑定select控件内容，根据url,基于select2,
$.fn.bindSelect2 = function (options) {
    var defaults = {
        id: "id",
        text: "text",
        search: false,
        url: "",
        param: [],
        change: null,
        success: null,
        theme: "bootstrap",
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    if (options.url != "") {
        $.ajax({
            url: options.url,
            data: options.param,
            dataType: "json",
            async: false,
            success: function (data) {
                $.each(data, function (i) {
                    $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
                });
                $element.select2({
                    minimumResultsForSearch: options.search == true ? 0 : -1
                });
                $element.on("change", function (e) {
                    if (options.change != null) {
                        options.change(data[$(this).find("option:selected").index()]);
                    }
                    $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                });
                if (!!options.success) {
                    options.success();
                }
            }
        });
    } else {
        $element.select2({
            minimumResultsForSearch: -1
        });
    }
}

$.documentContentHeight = null;
$.dataGridWidthCalcAmountObject = new Object();//用来触发第一次的计算
$.fn.dataGrid = function (options) {
    var $element = $(this);
    var tableId = $element.attr("id");
    if (options.container == "" || options.container == undefined || options.container == null) {//尝试去得到父级的id，如果没有，则自动生成一个
        if ($(this).parent().attr("id") == undefined) {
            var parentNewId = tableId + "-jqgrid-datagrid-container";
            $(this).parent().attr("id", parentNewId);
            options.container = "#" + parentNewId;
        }
        else {
            options.container = "#" + $(this).parent().attr("id");
        }
    }
    var defaults = {
        autoResetWidth: true,
        container: "",//父容器的选择器标识，如#id，等
        containerWidthDiff: 20,//与父容器的宽度的差值
        mtype: "POST",
        datatype: "json",
        styleUI: "Bootstrap",
        autowidth: true,
        viewrecords: true,
        multiselect: false,
        //forceFit: true,
        rownumbers: true, // 显示行号  
        rownumWidth: 50, // the width of the row numbers columns  
        autoScroll: false,
        height: "100%",
        width: '100%',
        rowNum: 15,
        rowList: [10, 20, 30],
        gridComplete: function () {
            //默认减小宽度
            //$.dataGridWidthCalcAmountObject[$(this).attr("id")]=0;
        },
        resizeStart: function () {
            //    $(this).closest(".ui-jqgrid-bdiv").css({ 'overflow-x': 'auto' });//设置滚动条
            //    $.dataGridWidthCalcAmountObject[tableId] = 0;
        },
        resizeStop: function () {
            $(this).closest(".ui-jqgrid-bdiv").css({ 'overflow-x': 'auto' });//设置滚动条
            $.documentContentHeight = $(document).height();
        }
    };
    var options = $.extend(defaults, options);
    var $grid = $element.jqGrid(options);
    if (options.autoResetWidth) {
        $.dataGridWidthCalcAmountObject[tableId] = 0;
        setInterval(function () {
            if ($.documentContentHeight == null) {
                $.documentContentHeight = $(document).height();
            }
            var needResetWidth = false;
            var tableWidth = $("#" + tableId).jqGrid().width();
            if (tableWidth == null || tableWidth < 10) {
                needResetWidth = true;
            }
            if (Math.abs($.documentContentHeight - $(document).height()) > 2 || $.dataGridWidthCalcAmountObject[tableId] < 1 || needResetWidth) {
                $("#" + tableId).setGridWidth($(options.container).parent().width() - options.containerWidthDiff);
                $.documentContentHeight = $(document).height();
            }
            $.dataGridWidthCalcAmountObject[tableId] = $.dataGridWidthCalcAmountObject[tableId] + 1;

        }, 500);
        $(window).resize(function () {
            $("#" + tableId).setGridWidth($(options.container).parent().width() - options.containerWidthDiff);
        });
    }
    return $grid;
}
//重新计算某一个列表的宽度
$.resetDataGridWidth = function (tableID) {
    $.dataGridWidthCalcAmountObject[tableID] = 0;
}
$.resetAllDataGridWidth = function () {
    $.each($.dataGridWidthCalcAmountObject, function (i, v) {
        $.dataGridWidthCalcAmountObject[i] = 0;
    })
}


$.S4 = function () {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
$.pedGuid = function () {
    var val = ($.S4() + $.S4() + "-" + $.S4() + "-" + $.S4() + "-" + $.S4() + "-" + $.S4() + $.S4() + $.S4());
    return val;
};
$.newID = function (p) {
    var val = '';
    $.ajax({
        url: '/Common/GetNewGUID',
        data: { str: p },
        type: 'post',
        datatype: 'json',
        async: false,
        success: function (r) {
            val = r;
        }
    });
    return val;
}
//左边补齐两位数
$.pedleft0 = function (obj) {
    return obj.toString().replace(/^[0-9]{1}$/, "0" + obj);
};
$.pedGetDate = function (format) {
    if (format == '' || format == null || format == undefined) {
        format = 'yyyy-MM-dd';
    }
    var dateflag = '-';
    var timeflag = ':';
    var isGetYear = true;
    var isGetMonth = true;
    var isGetDay = true;
    var isGetHour = true;
    var isGetMinute = true;
    var isGetSecond = true;
    var isGetMillisecond = true;

    if (format.indexOf('YYYY') < 0 && format.indexOf('yyyy') < 0) {
        isGetYear = false;
    }
    if (format.indexOf('MM') < 0 && format.indexOf('mm') < 0) {
        isGetMonth = false;
    }
    if (format.indexOf('DD') < 0 && format.indexOf('dd') < 0) {
        isGetDay = false;
    }
    if (format.indexOf('HH') < 0 && format.indexOf('hh') < 0) {
        isGetHour = false;
    }
    if (format.indexOf(':MM') < 0 && format.indexOf(':mm') < 0) {
        isGetMinute = false;
    }
    if (format.indexOf('SS') < 0 && format.indexOf('ss') < 0) {
        isGetSecond = false;
    }
    if (format.indexOf('.s') < 0 && format.indexOf('.s') < 0) {
        isGetMillisecond = false;
    }
    if (format.indexOf('-') > 0) {
        dateflag = '-';
    }
    else if (format.indexOf('/') > 0) {
        dateflag = '/';
    }
    else {
        if (format.indexOf(' ') < 0) {
            dateflag = '';
            timeflag = '';
        }
    }
    var nowtime = new Date();
    var year = nowtime.getFullYear();
    var month = $.pedleft0(nowtime.getMonth() + 1);
    var day = $.pedleft0(nowtime.getDate());
    var hour = $.pedleft0(nowtime.getHours());
    var minute = $.pedleft0(nowtime.getMinutes());
    var second = $.pedleft0(nowtime.getSeconds());
    var millisecond = nowtime.getMilliseconds(); millisecond = millisecond.toString().length == 1 ? "00" + millisecond : millisecond.toString().length == 2 ? "0" + millisecond : millisecond;
    var retdate = '';
    if (isGetYear) retdate = retdate + year ;
    if (isGetMonth) retdate = retdate + dateflag + month ;
    if (isGetDay) retdate = retdate + dateflag + day;
    if (dateflag != '') retdate = retdate + ' ';
    if (isGetHour) retdate = retdate + hour;
    if (isGetMinute) retdate = retdate + timeflag + minute;
    if (isGetSecond) retdate = retdate + timeflag + second;
    if (isGetMillisecond) retdate = retdate + '.' + millisecond;
    return retdate;
};
$.getPositionForInput = function (ctrl) {
    ctrl = ctrl[0];
    var CaretPos = 0;
    if (document.selection) { // IE Support 
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    } else if (ctrl.selectionStart || ctrl.selectionStart == '0') {// Firefox support 
        CaretPos = ctrl.selectionStart;
    }
    return (CaretPos);
}

var dateHelper = {
    //计算相差天数
    dateDiff: function (startDate, endDate) {
        var sdate = new Date(startDate.replace(/-/g, "/"));
        var eDate = new Date(endDate.replace(/-/g, "/"));
        var days = eDate.getTime() - sdate.getTime();
        var day = parseInt(days / (1000 * 60 * 60 * 24));
        return day;
    }
};

/* 当前页面高度 */
$.pageHeight = function () {
    return document.body.scrollHeight;
}

/* 当前页面宽度 */
$.pageWidth = function () {
    return document.body.scrollWidth;
}
//显示器高度
$.windowHeight = function () {
    return window.screen.height;
}
//显示器宽度
$.winddowWidth = function () {
    return window.screen.width;
}